package com.service.lotterySystem.service.impl;

import com.service.config.utils.IdUtil;
import com.service.config.utils.ModelMapperUtil;
import com.service.config.utils.Result;
import com.service.config.utils.ScanFilesWithRecursionUtils;
import com.service.lotterySystem.dao.ActivityInfoDao;
import com.service.lotterySystem.dao.VFilePhysicsInfoDao;
import com.service.lotterySystem.entity.ActivityInfo;
import com.service.lotterySystem.entity.VFilePhysicsInfo;
import com.service.lotterySystem.service.ExcelService;
import com.service.lotterySystem.service.VFilePhysicsInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;


/**
 * 物理文件消息表(VFilePhysicsInfo)表服务实现类
 *
 * @author makejava
 * @since 2021-05-18 19:56:30
 */
@Service("vFilePhysicsInfoService")
public class VFilePhysicsInfoServiceImpl implements VFilePhysicsInfoService {
    @Resource
    private VFilePhysicsInfoDao vFilePhysicsInfoDao;
    @Value("${spring.fileSeverIp}")
    private String systemIp;

    @Value("${spring.fileSeverDomain}")
    private String systemDomain;

    @Value("${spring.fileDic}")
    private String systemDic;

    @Value("${spring.fileDicDomain}")
    private String systemDicDomain;

    @Value("${spring.imageUrl}")
    private String imageUrl;
    @Resource
    private ExcelService excelService;
    @Resource
    private ActivityInfoDao  activityInfoDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public VFilePhysicsInfo queryById(String id) {
        return this.vFilePhysicsInfoDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<VFilePhysicsInfo> queryAllByLimit(int offset, int limit) {
        return this.vFilePhysicsInfoDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param vFilePhysicsInfo 实例对象
     * @return 实例对象
     */
    @Override
    public VFilePhysicsInfo insert(VFilePhysicsInfo vFilePhysicsInfo) {
        this.vFilePhysicsInfoDao.insert(vFilePhysicsInfo);
        return vFilePhysicsInfo;
    }

    /**
     * 修改数据
     *
     * @param vFilePhysicsInfo 实例对象
     * @return 实例对象
     */
    @Override
    public VFilePhysicsInfo update(VFilePhysicsInfo vFilePhysicsInfo) {
        this.vFilePhysicsInfoDao.update(vFilePhysicsInfo);
        return this.queryById(vFilePhysicsInfo.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.vFilePhysicsInfoDao.deleteById(id) > 0;
    }

    @Override
    public Result uploadServiceLogo(MultipartFile file, String aId, Integer isType) throws Exception {
        Map duplicate = duplicate(file);
        String url = "";
        VFilePhysicsInfo vFilePhysicsInfo = ModelMapperUtil.strictMap(duplicate.get("vFilePhysicsInfo"), VFilePhysicsInfo.class);
        Boolean.parseBoolean(duplicate.get("boolean").toString());
        ActivityInfo activityInfo = activityInfoDao.queryById(aId);
        if (activityInfo == null) {
            return  Result.failure("该活动已被删除，请刷新");
        }
        if (aId != null && !aId.equals("")) {
            uploadLogo(vFilePhysicsInfo, file);
            VFilePhysicsInfo vFilePhysicsInfo1 = vFilePhysicsInfoDao.queryById(vFilePhysicsInfo.getId());
            if (vFilePhysicsInfo1 != null) {
                url = getUrl(vFilePhysicsInfo);
                if (isType == 1) {
                    activityInfo.setAPosterUrl(url);
                }
                if (isType == 2) {
                    activityInfo.setABackgroundUrl(url);
                }
                activityInfoDao.update(activityInfo);
                // 上传图片绑定逻辑
                HashMap map = new HashMap();
                map.put("success","成功");
                map.put("code","00000");
                map.put("url",url);
                return  Result.ok().setData(map);
            }

        }
        HashMap map = new HashMap();
        map.put("errorMsg","店铺不存在");
        map.put("code",10001);
        return  Result.ok().setData(map);
    }
    public static String getUrl(VFilePhysicsInfo vFilePhysicsInfo) {
        return vFilePhysicsInfo.getFileseverdomain().concat(vFilePhysicsInfo.getFiledicdomain()).concat("/").concat(vFilePhysicsInfo.getFilename());
    }
    @Override
    public Result uploadExcel(MultipartFile file, String shopId,Integer type) throws Exception {
//        // 1.判断文件是否为空
//        if (file == null) {
//            return Result.failure(Constant.UPLOAD_EXCEL_EMPTY, Constant.UPLOAD_EXCEL_EMPTY_INFO);
//        }
//
//        // 2.判断上传内容是否符合要求
//        String fileName = file.getOriginalFilename();
//
//        // 判断是否是excel文件
//        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
//            return Result.failure(Constant.UPLOAD_EXCEL_ERROR, Constant.UPLOAD_EXCEL_ERROR_INFO);
//        }
//        ShopInfoReview shopInfoReview = shopInfoReviewDao.queryById(shopId);
//        List<NameListDto> nameListDtoList = excelService.batchImport(file);
//        List<NameListDto> cbList = nameListDtoList
//                .stream()
//                .collect(
//                        Collectors.collectingAndThen(
//                                Collectors.toCollection(
//                                        () -> new TreeSet<>(
//                                                Comparator.comparing(
//                                                        tc -> tc.getPhone() + ";" + tc.getUserName()))), ArrayList::new));
//        List<NameList> nameLists = ModelMapperUtil.strictMapList(cbList, NameList.class);
//        nameLists.removeIf(nameList -> nameList.getPhone() == null || "".equals(nameList.getPhone()) || nameList.getUserName() == null || "".equals(nameList.getUserName())); // 移除多余异常信息
//        if (type != null) {
//            if (type == Constant.USER_WHITE_LIST) {
//                nameLists.forEach(nameList -> {
//                    nameList.setShopId(shopId);
//                    nameList.setShopName(shopInfoReview.getShopName());
//                    nameList.setId(IdUtil.getStringId());
//                    nameList.setUpdateTime(new Date());
//                    nameList.setSsidName(shopInfoReview.getSsidName());
//                    nameList.setType(Constant.USER_WHITE_LIST);
//                });
//            }
//            if (type == Constant.USER_BLACK_LIST) {
//                nameLists.forEach(nameList -> {
//                    nameList.setShopId(shopId);
//                    nameList.setShopName(shopInfoReview.getShopName());
//                    nameList.setId(IdUtil.getStringId());
//                    nameList.setSsidName(shopInfoReview.getSsidName());
//                    nameList.setUpdateTime(new Date());
//                    nameList.setType(Constant.USER_BLACK_LIST);
//                });
//            }
//            NameList nameList = new NameList();
//            nameList.setShopId(shopId);
//            nameList.setType(type);
//            nameListDao.deleteByShopIdAndType(shopId,type);
//            nameListDao.insertBatch(nameLists);
//        }
        return Result.ok();
    }

    /**
     * 下载黑白名单
     * @param response
     * @param request
     * @param shopId
     * @param type
     */

    @Override
    public void downloadList(HttpServletResponse response, HttpServletRequest request, String shopId, Integer type) {
//        ExcelUtil<NameListDto> util = new ExcelUtil<>(NameListDto.class);
//        NameList nameList = new NameList();
//        String name = "";
//        String title = "";
//        if (type == Constant.USER_WHITE_LIST ) {
//            name = "白名单";
//            title = Constant.UPLOAD_EXCEL_TITLE_INFO;
//        }
//        if (type == Constant.USER_BLACK_LIST ) {
//            name = "黑名单";
//            title = Constant.UPLOAD_EXCEL_BLACK_LIST_TITLE_INFO;
//        }
//        nameList.setType(type);
//        nameList.setShopId(shopId);
//        List<NameList> nameLists = nameListDao.queryAll(nameList);
//        List<NameListDto> nameListDtoList = ModelMapperUtil.strictMapList(nameLists, NameListDto.class);
//        R r = util.exportExcel(title,nameListDtoList, name,2);
//        String fileName = (String) r.get("msg");
//        downloadFile(response, request, fileName);
    }

    /**
     * 上传logo
     * @param vFilePhysicsInfo
     * @throws Exception
     */
    @Transactional
    public void uploadLogo(VFilePhysicsInfo vFilePhysicsInfo, MultipartFile file) throws IOException {
        vFilePhysicsInfo.setFiledic(imageUrl);
        vFilePhysicsInfo.setFiledicdomain("");
        File file1 = createFile(vFilePhysicsInfo.getFiledic().concat("/").concat(vFilePhysicsInfo.getFilename()));
        createFile(file,file1);
        vFilePhysicsInfo.setFilemd5(ScanFilesWithRecursionUtils.getJdkFileMD5(file1.getPath()));
        vFilePhysicsInfoDao.insert(vFilePhysicsInfo);
    }
    private File createFile(String s) {
        File file = new File(s);
        return file;
    }
    private void createFile(MultipartFile file,File file1) throws IOException {
        file.transferTo(file1);
    }
    /**
     * 抽取共同代码
     * @param file
     * @return
     * @throws Exception
     */
    private Map duplicate(MultipartFile file) throws Exception {
        Map map = new HashMap();
        VFilePhysicsInfo vFilePhysicsInfo = new VFilePhysicsInfo();
        vFilePhysicsInfo.setId(IdUtil.getStringId());
        String originalFilename = file.getOriginalFilename();// 文件原始名称
        vFilePhysicsInfo.setFilerealname(originalFilename); // 设置文件真实名字
        int i = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(i + 1);
        boolean b1 = judgeFileType(substring);// 判断文件类型
        vFilePhysicsInfo.setFiletype(substring);
        vFilePhysicsInfo.setUpdtime(new Date());
        vFilePhysicsInfo.setAddtime(new Date());
        vFilePhysicsInfo.setFilename(UUID.randomUUID().toString().replace("-","")+"."+substring); // 对文件重命名
        vFilePhysicsInfo.setFileseverip(systemIp);// 服务器ip
        vFilePhysicsInfo.setFileseverdomain(systemDomain); // 服务器域名
        vFilePhysicsInfo.setUpdtime(new Date());
        vFilePhysicsInfo.setStatus("1");
        vFilePhysicsInfo.setDelflag("0");
        map.put("vFilePhysicsInfo",vFilePhysicsInfo);
        map.put("boolean",b1);
        return map;
    }
    /**
     * 判断文件类型
     * @param substring
     * @return
     */
    private boolean judgeFileType(String substring) {
        if (substring.equals("gif")) {
            return true;
        }
        if (substring.equals("jpg")) {
            return true;
        }
        if (substring.equals("jpeg")) {
            return true;
        }
        if (substring.equals("png")) {
            return true;
        }
        if (substring.equals("GIF")) {
            return true;
        }
        if (substring.equals("JPG")) {
            return true;
        }
        if (substring.equals("JPEG")) {
            return true;
        }
        if (substring.equals("PNG")) {
            return true;
        }
        return false;
    }
}
